package com.platform.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * describe:自定义自动实现填充
 *
 * @author rainly
 * @date 2020/01/09
 * @time 4:23 下午
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 获得mybatisPlus设置的全局逻辑删除字段值
     */
    @Value("${mybatis-plus.global-config.db-config.logic-delete-field}")
    private String deleteField;

    /**
     * 获得mybatisPlus设置的全局逻辑未删除值
     */
    @Value(value = "${mybatis-plus.global-config.db-config.logic-not-delete-value}")
    private String notDeleteValue;

    /**
     * 插入时自动实现填充
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("插入自动填充");
        //如果没有设置的全局逻辑删除字段值，则不需自动填充
        if (StringUtils.isNotEmpty(deleteField)){
            Object flag = this.getFieldValByName(deleteField,metaObject);
            //如果在插入时已经设置值了，则不再进行自动填充
            if (null == flag){
                this.strictInsertFill(metaObject,deleteField,String.class,notDeleteValue);
            }
        }

        String user = "user";

        Object createBy = this.getFieldValByName("createBy", metaObject);
        if(null == createBy){
            this.strictInsertFill(metaObject, "createBy", String.class, user);
        }
        Object createDate = this.getFieldValByName("createDate", metaObject);
        if(null == createDate){
            this.strictInsertFill(metaObject, "createDate", LocalDateTime.class, LocalDateTime.now());
        }
        Object updateBy = this.getFieldValByName("updateBy", metaObject);
        if(null == updateBy){
            this.strictInsertFill(metaObject, "updateBy", String.class, user);
        }
        Object updateDate = this.getFieldValByName("updateDate", metaObject);
        if(null == updateDate){
            this.strictInsertFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
        }
    }

    /**
     * 更新时自动实现填充
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("更新自动填充");
        String user = "user";

        Object updateBy = this.getFieldValByName("updateBy", metaObject);
        if(null == updateBy){
            this.strictUpdateFill(metaObject, "updateBy", String.class, user);
        }
        Object updateDate = this.getFieldValByName("updateDate", metaObject);
        if(null == updateDate){
            this.strictUpdateFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
        }
    }
}
